/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CS3200JFrame.java
 *
 * Created on Oct 25, 2009, 11:45:34 AM
 */
package com.example;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Dilan
 * userinterface GUI
 * action performed
 * get clipboard data
 */
public class UserInterface extends javax.swing.JFrame {

    String word, astring, subString, subString2, Settings = "";
    int beginIndex, endIndex, dotAt, stringLength = 0;
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // get clipboard data

    public UserInterface() throws UnsupportedFlavorException {

        initComponents();
        Word.setText("");
        setProxy.setText(null);
        setPort.setText(null);
        displayPanal.removeAll();

        try {
            Word.setText((String) clipboard.getData(DataFlavor.stringFlavor)); //get clipboard data
        } catch (UnsupportedFlavorException ex) {
            Word.setText("");
        } catch (IOException ex) {
            Word.setText("");
        }

        /**
         * if user already define a proxy settings, load them when loading
         */
        try {
            FileInputStream inSettings = new FileInputStream("C:\\Temp\\settings.txt");
            BufferedReader bufferSettings = new BufferedReader(new InputStreamReader(inSettings));

            Settings = bufferSettings.readLine().toString();

            if (Settings.equalsIgnoreCase("noSettings")) {//proxy setting not defined
                proxyOn.setSelected(false);
                setProxy.setEnabled(false);
                setPort.setEnabled(false);
            } else {                                     //proxy setting already define
                int indexAt = Settings.indexOf(' ');
                proxyOn.setSelected(true);
                setProxy.setEnabled(true);
                setPort.setEnabled(true);

                setProxy.setText(Settings.substring(0, indexAt)); //proxy
                setPort.setText(Settings.substring(indexAt + 1));   //port
            }
        } catch (java.io.IOException ex) {
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDesktopPane1 = new javax.swing.JDesktopPane();
        Word = new javax.swing.JTextField();
        Ok = new javax.swing.JButton();
        cancle = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        displayPanal = new javax.swing.JTextArea();
        proxyOn = new javax.swing.JCheckBox();
        setProxy = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        setPort = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Dictionary");
        setBounds(new java.awt.Rectangle(350, 250, 0, 0));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setMaximizedBounds(getMaximizedBounds());
        setResizable(false);

        Word.setToolTipText("Enter word to get meaning");
        Word.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                UserInterface.this.keyPressed(evt);
            }
        });

        Ok.setText("OK");
        Ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OkActionPerformed(evt);
            }
        });

        cancle.setText("CANCEL");
        cancle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancleActionPerformed(evt);
            }
        });

        displayPanal.setColumns(20);
        displayPanal.setEditable(false);
        displayPanal.setRows(5);
        jScrollPane1.setViewportView(displayPanal);

        proxyOn.setText("Use Proxy");
        proxyOn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                proxyOnActionPerformed(evt);
            }
        });

        setProxy.setToolTipText("set proxy");

        jLabel1.setText("HTTP Proxy:");

        setPort.setToolTipText("set port");

        jLabel2.setText("Port:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(Word, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(proxyOn, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(Ok, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                                .addComponent(cancle))
                            .addComponent(setProxy, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                            .addComponent(setPort, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Word, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Ok)
                    .addComponent(cancle))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(setProxy, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(proxyOn, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(setPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(17, 17, 17)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                .addContainerGap())
        );

        Word.getAccessibleContext().setAccessibleName("");
        Word.getAccessibleContext().setAccessibleDescription("Word to get meaning");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancleActionPerformed
        /**
         * save defined proxy setting when closed
         */
        if (proxyOn.isSelected() && setProxy.getText().isEmpty() == false && setPort.getText().isEmpty() == false) {
            try {
                File fileSettings = new File("C:\\Temp\\settings.txt");// open file to save web reply
                Writer outputSettings = new BufferedWriter(new FileWriter(fileSettings));

                outputSettings.append(setProxy.getText() + " "); //save proxy to file
                outputSettings.append(setPort.getText());  //save port to file
                outputSettings.close();
            } catch (java.io.IOException e) {
                e.notifyAll();

            }
        } else {
            try {
                File fileSettings = new File("C:\\Temp\\settings.txt");// open file to save web reply
                Writer outputSettings = new BufferedWriter(new FileWriter(fileSettings));

                outputSettings.append("noSettings"); //save predefined word to file if no proxy set
                outputSettings.close();
            } catch (java.io.IOException e) {
                e.notifyAll();
            }
        }
        dispose(); //get closed

    }//GEN-LAST:event_cancleActionPerformed

    private void OkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OkActionPerformed

        word = Word.getText();

        if (Word.getText().isEmpty()) {
            /*No input word */
            JOptionPane.showMessageDialog(rootPane, "Enter Word", "Error", WIDTH);

        } else if (proxyOn.isSelected() && setProxy.getText().isEmpty() == false && setPort.getText().isEmpty() == false) {
            /*Proxy on and input fields are filled*/
            openURL active = new openURL();
            active.setProxy(setProxy.getText(), setPort.getText());
            active.URL(word);
            displayPanal.setText("");
            display();

        } else if (proxyOn.isSelected() && (setProxy.getText().isEmpty() || setPort.getText().isEmpty())) {
            /*Proxy on and proxy or port field not filled */
            JOptionPane.showMessageDialog(rootPane, "Set Proxy First", "Error", WIDTH);

        } else if (Word.getText().isEmpty() == false && proxyOn.isSelected() == false) {
            /*proxy off*/
            openURL active = new openURL();
            active.setProxy("", "");
            active.URL(word);
            displayPanal.setText("");
            display();
        }
    }//GEN-LAST:event_OkActionPerformed

    private void proxyOnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_proxyOnActionPerformed

        if (proxyOn.isSelected()) {
            /*proxy on */
            setProxy.setEnabled(true);
            setPort.setEnabled(true);
        } else {
            /*Proxy off*/
            setProxy.setEnabled(false);
            setPort.setEnabled(false);
        }
    }//GEN-LAST:event_proxyOnActionPerformed

    private void keyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) { //action to perform when Enter key pressed
            this.OkActionPerformed(null);
        } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { //action to perform when Escape key pressed
            this.cancleActionPerformed(null);
        }
    }//GEN-LAST:event_keyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new UserInterface().setVisible(true);
                } catch (UnsupportedFlavorException ex) {
                    Logger.getLogger(UserInterface.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Ok;
    private javax.swing.JTextField Word;
    private javax.swing.JButton cancle;
    private javax.swing.JTextArea displayPanal;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JCheckBox proxyOn;
    private javax.swing.JTextField setPort;
    private javax.swing.JTextField setProxy;
    // End of variables declaration//GEN-END:variables

    /*
     * display text reply from dictionary.com in text area
     */
    private void display() {

        try {
            FileInputStream in = new FileInputStream("C:\\Temp\\write.txt");
            BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);

            String il;

            while ((il = buffer.readLine()) != null) {
                printWriter.println(il);
            }
            if (stringWriter.getBuffer().toString().isEmpty()) {
                /*input text file is empty*/
                JOptionPane.showMessageDialog(rootPane, "Unable to Establish the connection", "Connection Error", WIDTH);
            } else {
                /*get required part from the reply*/
                astring = stringWriter.getBuffer().toString();

                beginIndex = astring.indexOf("content="); //definition of the word starts with "content="
                endIndex = astring.indexOf("Google&#39;s");//definition ot the word ends with "Google&#39;s"

                subString = astring.substring(beginIndex + 69, endIndex - 3); //create a substring with the whole definition
                stringLength = subString.length(); //determine the length of the sbstring
                dotAt = subString.indexOf("."); //determine wether definition with more parts

                /*according to the length of the definition arrange the output to display on the text area*/
                if (stringLength <= 72) {
                    displayPanal.append(subString);
                } else {
                    if (stringLength <= 144 && stringLength >= 72) {
                        if (' ' == subString.charAt(72)) {
                            displayPanal.append(subString.substring(0, 72) + "\n");
                            displayPanal.append(subString.substring(72));
                        } else {
                            for (int count = 72; count < 1;
                                    count = count - 1) {
                                if (' ' == subString.charAt(count)) {
                                    displayPanal.append(subString.substring(0, count) + "\n");
                                    displayPanal.append(subString.substring(count));
                                    continue;
                                }
                            }
                        }
                    } else if (stringLength <= 216 && stringLength >= 144) {

                        if (' ' == subString.charAt(72)) {
                            displayPanal.append(subString.substring(0, 72) + "\n");
                            if (' ' == subString.charAt(144)) {
                                displayPanal.append(subString.substring(72, 144));
                            } else {
                                for (int count = 144; count > 100; --count) {
                                    if (' ' == subString.charAt(count)) {
                                        displayPanal.append(subString.substring(72, count) + "\n");
                                        displayPanal.append(subString.substring(count + 1));
                                        count = 90;
                                        continue;
                                    }

                                }
                            }
                        } else {

                            for (int count = 72; count > 65; --count) {
                                if (' ' == subString.charAt(count)) {
                                    System.out.println("216 144");
                                    displayPanal.append(subString.substring(0, count) + "\n");
                                    displayPanal.append(subString.substring(count + 1, 72));
                                    count = 34;
                                    continue;
                                }
                            }
                            if (' ' == subString.charAt(144)) {
                                displayPanal.append(subString.substring(72, 144) + "\n");
                            } else {
                                for (int count = 144; count > 120; count--) {
                                    if (' ' == subString.charAt(count)) {
                                        displayPanal.append(subString.substring(72, count) + "\n");
                                        displayPanal.append(subString.substring(count + 1));
                                        count = 110;
                                        continue;
                                    }
                                }
                            }
                        }

                    }
                }
            }

            printWriter.flush(); //flush the stream

            in.close(); //close the file
            buffer.close();
            stringWriter.close();
            printWriter.close();
        } catch (java.io.IOException ex) {
            displayPanal.setText("Error occered");
        }
    }
}
